﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using DynamicComparer;
using System.IO;

namespace Shuba.Web.bulk_upload
{
    /*
     *  NAME TABLE  :   - TBL_MS_SPADA_FILE_VERSION
     *                  - TBL_MS_SPADA_FILE_VERSION_TMP
     *  REFERENCES  :   - Shuba.Model.SPADAFileInfo.cs
     *                  - Shuba.Data.SPADAFile.cs
     *                  - Shuba.Business.SPADAFile.cs
     *  PROCEDURE   :   - PROC_APPROVAL_SPADA_FILE_VERSION
    */
    public partial class SPADA_File : basePage
    {
        string msg = "", myid = "";
        bool IsView, IsAdd, IsEdit, IsDelete, IsChecker;
        Int16 berhasil = 0, gagal = 0;

        private void FileStatus(string VarToSplit, string VarPathUpload,string VarActType)
        {
            try
            {
                myid = VarToSplit;

                if (VarActType == "UPLOAD")
                {
                    //if (File.Exists(VarPathUpload + '\\' + myid))
                    //{
                        //File.Delete(VarPathUpload + '\\' + myid);
                    //}
                    //File.Move(VarPathUpload + '\\' + VarToSplit, VarPathUpload + '\\' + VarToSplit); //myid);
                }
                else if (VarActType == "DELETE")
                {
                    if (File.Exists(VarPathUpload + '\\' + myid))
                    {
                        File.Delete(VarPathUpload + '\\' + myid);
                    }
                    if (Directory.Exists(VarPathUpload)) Directory.Delete(VarPathUpload);                    
                }
            }
            catch (Exception) { }           
        }
        
        private void BindData()
        {
            Shuba.Business.SPADAFile _SPADAFile = new Shuba.Business.SPADAFile();
            List<Shuba.Model.SPADAFileInfo> list = _SPADAFile.GetList(txtSearch.Text);

            if (ViewState["SortEx"].ToString().Trim() != "")
            {
                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<Shuba.Model.SPADAFileInfo> comparer = new DynamicComparer<Shuba.Model.SPADAFileInfo>(sort);
                list.Sort(comparer);
            }

            gvList.DataSource = list;
            gvList.DataBind();

            if (IsEdit || IsDelete) gvList.Columns[gvList.Columns.Count- 1].Visible = true;
            else gvList.Columns[gvList.Columns.Count -1].Visible = false;

            //FOR APPROVAL GRID
            if (IsChecker)
            {
                BindApprovalData();

                if (ApprovalGrid.Rows.Count > 0) { ApprovalPnl.Visible = true; } else { ApprovalPnl.Visible = false; }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string acl = GetUserAccess("MSTR_SPADA_FILE_VERSION");

            IsView = IsUserView(acl);
            IsAdd = IsUserAdd(acl);
            IsEdit = IsUserEdit(acl);
            IsDelete = IsUserDelete(acl);
            IsChecker = IsUserChecker(acl);

            if (!IsView)
            {
                msg = GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
            }

            if (!IsPostBack)
            {
                InitSort();
                BindData();
                LabelTitle.Text = GetPageTitle("MSTR_SPADA_FILE_VERSION");

                if (IsAdd)
                {
                    btnUpload.Enabled = true;
                }
                else
                {
                    btnUpload.Enabled = false;
                }
            }
        }

        protected void gvList_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Remove":
                    string id = e.CommandArgument.ToString();
                    Shuba.Business.SPADAFile _SPADAFile = new Shuba.Business.SPADAFile();
                    Shuba.Model.SPADAFileInfo _bi = _SPADAFile.GetInfo(id);
                    if (_SPADAFile.CheckIsUsedFileUpdate(_bi.DATE_FILE_UPLOAD))
                    {
                        Alert("This file can not delete. This file is latest update");
                    }
                    else
                    {
                        _bi.UPDATE_BY = HttpContext.Current.User.Identity.Name;
                        _bi.UPDATE_DATE = ProcessingDate();
                        _bi.ACT_TYPE = "DELETE";

                        try
                        {
                            _SPADAFile.Save(_bi);
                            AddLog("DELETE", "DELETE SPADA FILE VERSION");
                        }
                        catch (Exception ex)
                        {
                            msg = ex.Message.ToString();

                            ErrBox.Visible = true;
                            ErrMsg.Text = msg;
                        }
                        if (msg == "") BindData();
                    }
                    break;
            }
        }

        protected void gvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvList.PageIndex = e.NewPageIndex;
            BindData();
        }

        protected void gvList_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression, e.SortDirection.ToString());
            ViewState["SortEx"] = e.SortExpression;
            gvList.PageIndex = 0;
            BindData();
        }

        protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton btnDelete = (LinkButton)e.Row.FindControl("btnDelete");

                if (IsDelete) btnDelete.Enabled = true; else btnDelete.Enabled = false;

                if (!string.IsNullOrEmpty(e.Row.Cells[2].Text)) e.Row.Cells[2].Text = FormatSizeBinary(Convert.ToInt64(e.Row.Cells[2].Text), 2); 
            }
        }

        /// <summary>Format an amount of bytes to a more readible notation with binary notation symbols</summary>
        /// <param name="size">Required. Int64. The raw amount of bytes</param>
        /// <param name="decimals">Optional. Int32. The amount of decimals you want to have displayed in the notation</param>
        public static string FormatSizeBinary(Int64 size, Int32 decimals)
        {
            // By De Dauw Jeroen - April 2009 - jeroen_dedauw@yahoo.com
            String[] sizes = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
            Double formattedSize = size;
            Int32 sizeIndex = 0;
            while (formattedSize >= 1024 && sizeIndex < sizes.Length)
            {
                formattedSize /= 1024;
                sizeIndex += 1;
            }
            return Math.Round(formattedSize, decimals) + sizes[sizeIndex];
        }

        /*======================================
        APPROVAL GRID START HERE
        =======================================
        */
        private void BindApprovalData()
        {
            Shuba.Business.SPADAFile _SPADAFile = new Shuba.Business.SPADAFile();
            List<Shuba.Model.SPADAFileInfo> list = _SPADAFile.GetListApproval(HttpContext.Current.User.Identity.Name);

            if (ViewState["SortEx"].ToString().Trim() != "")
            {
                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<Shuba.Model.SPADAFileInfo> comparer = new DynamicComparer<Shuba.Model.SPADAFileInfo>(sort);
                list.Sort(comparer);
            }
            ApprovalGrid.DataSource = list;
            ApprovalGrid.DataBind();
        }

        protected void ApprovalGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            ApprovalGrid.PageIndex = e.NewPageIndex;
            BindApprovalData();
        }

        protected void ApprovalGrid_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression, e.SortDirection.ToString());
            ViewState["SortEx"] = e.SortExpression;
            ApprovalGrid.PageIndex = 0;
            BindApprovalData();
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            berhasil = 0;
            gagal = 0;

            foreach (GridViewRow row in ApprovalGrid.Rows)
            {
                CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");
                string id = Convert.ToString(ApprovalGrid.DataKeys[row.RowIndex].Value.ToString());
                
                if (chkItemSelect.Checked)
                {
                    Approve(id, true);
                }
            }
            if (berhasil > 0 || gagal > 0)
            {
                msg = "Approval Notification\\n\\nSuccessfully Approve : " + berhasil + " Record(s)\\n\\nFailed to Approve : " + gagal + " Record(s)";
                if (gagal > 0) msg += "\\n\\nPlease make sure:\\n- CHANNEL ID is correct \\n- Prospect and Debtor Type is correct";
            }
            BindData();
            Alert(msg);
        }

        private void Approve(string id, bool IsApprove)
        {
            Shuba.Business.SPADAFile _SPADAFile = new Shuba.Business.SPADAFile();
            Shuba.Model.SPADAFileInfo bi = new Shuba.Model.SPADAFileInfo();

            bi = _SPADAFile.GetApprovalByID(id);
            bi.UPDATE_BY = HttpContext.Current.User.Identity.Name;
            bi.UPDATE_DATE = ProcessingDate();
            string[] mysplit = bi.FILE_NAME_UPLOAD.Split(new char[] {'~'});           
            string ActType = bi.ACT_TYPE;

            if (IsApprove)
            {
                if (bi.DATE_FILE_UPLOAD.ToString() != "")
                {
                    FileStatus(bi.FILE_NAME_UPLOAD, bi.PATH_FILE_UPLOAD, ActType);
                    bi.FILE_NAME_UPLOAD = bi.FILE_NAME_UPLOAD; //mysplit.GetValue(0).ToString();
                    _SPADAFile.Approve(ActType, bi.ROWNUM,bi.FILE_NAME_UPLOAD,bi.DATE_FILE_UPLOAD );
                    AddLog("APPROVAL", "APPROVE SPADA FILE VERSION");

                    berhasil += 1;
                }
                else
                {
                    gagal += 1;
                }
            }
            else
            {
                _SPADAFile.Reject(bi.ROWNUM);
                if (bi.ACT_TYPE == "UPLOAD") DeleteFiles(bi.PATH_FILE_UPLOAD, bi.FILE_NAME_UPLOAD);
                AddLog("APPROVAL", "REJECT SPADA FILE VERSION");
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }

        protected void btnReject_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in ApprovalGrid.Rows)
            {
                CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");
                string id = Convert.ToString(ApprovalGrid.DataKeys[row.RowIndex].Value.ToString());
                if (chkItemSelect.Checked)
                {
                    Approve(id, false);
                }
            }
            msg = GetGlobalResourceObject("Messages", "NoApprove").ToString();
            BindData();
            Alert(msg);
        }

        private void DeleteFiles(string directory, string filename)
        {
            try
            {
                if (File.Exists(String.Format("{0}\\{1}", directory, filename))) File.Delete(String.Format("{0}\\{1}", directory, filename));
                if (Directory.Exists(directory)) Directory.Delete(directory);
            }
            catch (Exception)
            {
            }
        }
    }
}